<?php
/**
 * Created by PhpStorm.
 * User: win7
 * Date: 2018/5/11 0011
 * Time: 19:25
 */
namespace Wx\Controller;
use Think\Controller;
use Wx\Controller\AutoController;
use Wx\Model\shareModel;

class ProdetailController extends CommonController
{
    public function Index(){
        $member=D('member');
		$shop_store=D('shop_store');//门店表
		$shop_spellgroup=D('shop_spellgroup');//商品表
		$shop_spellgroup_copy=D('shop_spellgroup_copy');//副本表
        //判断是否为用户支付成功后跳转来的页面
        $share = intval(I('share'));
        if($share==1){
			//进行再次跳转，构建传送付款的商品id和该小区副本id
            // 获取session中用户刚付款的商品id	session('sg_id')
			$shop_spellgroup_copy=M('shop_spellgroup_copy');
			$getcopy=$shop_spellgroup_copy
			->alias('sc')
			->join("xtws_shop_spellgroup_order so on sc.id=so.c_id")
			->where("sc.sg_id=".session('sg_id')." and so.u_id=".session('u_id'))
			->order("so.id DESC")
			->field("so.*")
			->find();
			
            redirect('/Wx/Prodetail/Index/id/'.session('sg_id').'/c_id/'.$getcopy['c_id'].'/u_id/'.session('u_id').'/');            
            //session('sg_id',null);   //清除该session
			die; 
        }
        // 调用检查产品状态的方法
        $auto = new AutoController();
        $auto->checkProduct($_GET['id']);
        $shop=$shop_spellgroup->where("id=".$_GET['id'])->find();
//        die;
		//产品已经下架
		if( empty($shop) || $shop['state']==4){
			redirect('/Wx/SoldOut/index');
			die;
		}
		if($shop['limit_state']==1){//判断商品是否限购
            //判断用户是否购买了限购商品
            //$orderMap['sc.sg_id'] = array('in',$shop['id'].','.$shop['oldid']);
            $orderMap['sc.sg_id'] = array('in',"494,557,561");
            $orderMap['so.u_id'] = session('u_id');
            $orderMap['so.state'] = array('not in','3,8');
            $sgOrder = $shop_spellgroup_copy
                ->alias('sc')
                ->join("xtws_shop_spellgroup_order so on sc.id=so.c_id")
//                ->where("sc.sg_id=".$shop['id']." and so.u_id=".session('u_id')." and so.state not in ('3,8')")
                ->where($orderMap)
                ->find();
//            dump(3);
//            dump($sgOrder);
//            $a = $shop_spellgroup_copy->getLastSql();
//            dump($a);
            if($sgOrder!=''){
                $isOrder = 1;
            }else{
                $isOrder = 0;
            }
        }else{
            $isOrder = 0;
        }
//        dump($isOrder);
        $this->assign('isOrder',$isOrder);

		//显示代收人信息
		if($_GET['u_id']>0){
			$proxy_info=array();
			$get_p_info=$member->where("id=".$_GET['u_id'])->find();
			$proxy_info['realname']=$get_p_info['realname'];
			$proxy_info['mobile']=$get_p_info['mobile'];
			$shop_store=D('shop_store');
			$get_s=$shop_store->where("c_id=".$get_p_info['c_id'])->find();
			$proxy_info['address']=$get_s['address'];
			$this->assign('proxy_info',$proxy_info);//
		}//end if
		if(session('u_id')>0){
			$c_id=$member->where('id='.session('u_id'))->getField('c_id');//小区id
			if($c_id>0)$self_copy_id=$shop_spellgroup_copy->where("sg_id=".$_GET['id']." and c_id =".$c_id)->getField('id');//本小区副本
		}
		//该副本拼团用户列表(朋友分享展示的是朋友的自提点和朋友社区用户拼团情况)
		//if($_GET['c_id']!='' || $self_copy_id>0){
		if($_GET['c_id']!='' ){
        	$copy_id=$_GET['c_id'];//小区副本
			//dump($copy_id);
			$shop['copy_id']=$copy_id;
			$this->assign('sg_id',session('sg_id'));//用户刚付款的商品id--
			$this->assign('c_id',$copy_id);//社区副本分享
			
		}else{}//end if
		//自提信息_____________________________________
		//dump($shop['type']);
		if($shop['type']==1){
			//门店发布的拼团，只存在该门店小区下这一个副本
			$s_id=$shop['s_id'];//发布该拼团商品的门店id
			$getshop=$shop_store->where("id=".$s_id)->find();//店铺
			//dump($s_id);
			if($getshop['id']>0){
				$shop['c_shop_have']=1;
				$shop['c_shop_name']=$getshop['storename'];
				$shop['c_shop_address']=$getshop['address'];
			}else{
				$shop['c_shop_have']=0;//没有门店
			}//end if
			//如果是门店的，查找门店副本
			$copy_id=$shop_spellgroup_copy->where("sg_id=".$shop['id'])->getField('id');
			if($copy_id>0){
				//有副本
				$shop['copy_id']=$copy_id;
				$shop['c_do']=1;//社区已经拼团
				goto md_mb_ls;
			}else{
				//无副本
				$shop['c_do']=0;//社区未拼团
			}
		}else{
			//乡村拼团
			if($_GET['c_id']!='' ){
				//有副本
				$copy_id=$_GET['c_id'];//小区副本
				//dump($copy_id);
				$shop['copy_id']=$copy_id;
				$shop['c_do']=1;//社区已经拼团
				$c_id=$shop_spellgroup_copy->where("id=".$copy_id)->getField('c_id');//小区
				$getshop=$shop_store->where("status=1 and c_id=".$c_id)->find();//店铺
				if($getshop['id']>0){
					$shop['c_shop_have']=1;
					$shop['c_shop_name']=$getshop['storename'];
					$shop['c_shop_address']=$getshop['address'];
				}else{
					$shop['c_shop_have']=0;//没有门店
				}//end if
				//******下面代码同下面if代码段******* 
				goto md_mb_ls;
			}else{
				//无副本
				$shop['c_do']=0;//社区未拼团
				//显示登录状态的用户小区下门店信息
				if(session('u_id')>0){
					$c_id=$member->where("id=".session('u_id'))->getField('c_id');//小区
					$getshop=$shop_store->where("status=1 and c_id=".$c_id)->find();//店铺
					if($getshop['id']>0){
						$shop['c_shop_have']=1;
						$shop['c_shop_name']=$getshop['storename'];
						$shop['c_shop_address']=$getshop['address'];
					}else{
						$shop['c_shop_have']=0;//没有门店
					}//end if
				}
			}
			
		}//end if
		//自提信息_____________________________________end
		//本社区拼团用户列表
		if($self_copy_id>0){
			$copy_id=$self_copy_id;//本小区副本
			md_mb_ls:
			$shop['c_do']=1;//社区已经拼团
			//分享-查找拼团人信息 
			$shop_spellgroup_order=D('shop_spellgroup_order');//订单表
			$getmem=$shop_spellgroup_order->where("state>=1 and c_id=".$copy_id)->select();//dump($getmem);
			//查询用户 图片 姓名 家乡 
			//dump(count($getmem));
			$buynum=0;//已经付款订单份数
			foreach($getmem as $i=>$one){
				$getuser=$member->where("id=".$one['u_id'])->find();
				$getmem[$i]['avatar']=$getuser['avatar'];
				$getmem[$i]['nickname']=$getuser['nickname'];
				$getmem[$i]['hometown']=$getuser['hometown'];
				$buynum=$buynum+$one['num'];
			}//end for
			$shop['c_neednum']=$shop['min_num']-$buynum;//还差几人成团
			if($buynum==0)$shop['c_do']=0;//副本生成了，但是没人付款
			//判断小区有没有门店
			//通过小区查门店信息
			$shop_spellgroup_copy=D('shop_spellgroup_copy');//副本表
			//找到该副本小区
			$getcom=$shop_spellgroup_copy->where("id=".$copy_id)->find();//dump($getcom);
			$shop['comid']=$getcom['c_id'];//分享的小区id
			$shop['c_havenum']=$getcom['num'];//本社区已经拼团 

			$this->assign('userli',$getmem);//本社区拼团用户列表
		}
		//查商品单位
		$category=D('category');
		$getc=$category->where("id=".$shop['unit'])->find();
		$shop['unit']=$getc['title'];
		//图片数组转换
		$shop['h_imgs']=explode(',',$shop['h_imgs']);
		//销售份数
		$shop['actual_num']=$shop_spellgroup_copy->where("sg_id=".$shop['id'])->sum('num');
		//农户信息
		if($shop['type']==0){
			$member_farmers=D('member_farmers');
			$area=D('area');
			$getnhinfo=$member->where("id=".$shop['u_id'])->find();//农户信息
			$this->assign('getnhinfo',$getnhinfo);
			$getfarm=$member_farmers->where("u_id=".$shop['u_id'])->find();//农户信息-地址
			$getarea=$area->where("id=".$getfarm['a_id_1'])->find();
			$getfarm['a1']=$getarea['name'];
			$getarea=$area->where("id=".$getfarm['a_id_2'])->find();
			$getfarm['a2']=$getarea['name'];
			$getarea=$area->where("id=".$getfarm['a_id_3'])->find();
			$getfarm['a3']=$getarea['name'];
			$getarea=$area->where("id=".$getfarm['a_id_4'])->find();
			$getfarm['a4']=$getarea['name'];
			$getarea=$area->where("id=".$getfarm['a_id_5'])->find();
			$getfarm['a5']=$getarea['name'];
			$this->assign('getfarm',$getfarm);
		}
		//dump(session());
		//检测用户是否登录
		if(session('u_id')>0){
			//登录，查小区副本
			$getinfo=$member->where('id='.session('u_id'))->find();
			if($getinfo['c_id']>0){
				//已经绑定小区
				//查副本还差多少份
				$shop_spellgroup_copy=D('shop_spellgroup_copy');//副本表
				$getcopy=$shop_spellgroup_copy->where("sg_id=".$shop['id']." and c_id=".$getinfo['c_id'])->find();
				
				//dump($getcopy); 
				if($getcopy['num']>0){
					if($_GET['c_id']!=''){}else{$shop['copy_id']=$getcopy['id'];}
					$shop['c_do']=1;//社区已经拼团
					$shop['c_havenum']=$getcopy['num'];//本社区已经拼团
					if($getcopy['num']==0)$shop['c_do']=0;//副本生成了，但是没人付款
					$shop['c_neednum']=$shop['min_num']-$getcopy['num'];
					if($shop['min_num']-$getcopy['num']<0)$shop['orsuccess']=1;//拼团成功
					
					if($_GET['c_id']>0){}else{
						//有人尝试或者已经开团-查找拼团人信息
						/*$shop_spellgroup_order=D('shop_spellgroup_order');//订单表
						$getmem=$shop_spellgroup_order->where("state=1 and c_id=".$getcopy['id'])->select();
						//查询用户 图片 姓名 家乡 
						
						foreach($getmem as $i=>$one){
							$getuser=$member->where("id=".$one['u_id'])->find();
							$getmem[$i]['avatar']=$getuser['avatar'];
							$getmem[$i]['nickname']=$getuser['nickname'];
							$getmem[$i]['hometown']=$getuser['hometown'];
						}//end for
						
						$this->assign('userli',$getmem);//本社区拼团用户列表*/
					}//endif 
				}else{
					//本社区还没有开团
					
				}//end if
				
			}else{
				//没有小区
			}
			// 判断是否收藏了该商品
			$collect = M('shop_spellgroup_collection')->where(array('u_id'=>session('u_id'),'group_id'=>I('id')))->find();
			if($collect!=''){
			    $shop['collect_status'] = 1;
            }else{
                $shop['collect_status'] = 0;
            }

		}else{
			//未登录
		}//end if
		//dump($shop['c_shop_have']);
		//分享简介截取详情前30个汉字
		$shop['share_info']=str_replace(array("\r\n", "\r", "\n","　"), "", $shop['content']);
		$shop['share_info']=preg_replace(array("(<[^>]*>)" ),"",$shop['share_info']);//去掉所有标签
		$shop['share_info']=str_replace(' ', '', $shop['share_info']);//去掉空格
		$shop['share_info']=mb_substr($shop['share_info'],0,30,'utf-8');
		$this->assign('shop',$shop);
		$this->assign('focus',session('focus'));//是否关注
		
		//获取当前网页，个人信息在补充完成后跳转到该详情页面
		$path =  $_SERVER['REQUEST_URI'];
		session("pro_url",$path);
//微信分享
		$wxshare=new shareModel(C('WX_API.appid'),C('WX_API.secret'));
		$signPackage=$wxshare->getSignPackage();
/*
*
array(6) {
  ["appId"] => string(18) "wx6a0daaedc4d00100"
  ["nonceStr"] => string(16) "5cKMHQADQTbRkv2f"
  ["timestamp"] => int(1527576256)
  ["url"] => string(59) "http://www.xiangtws.com/index.php/Wx/Prodetail/index/id/20/"
  ["signature"] => string(40) "a70ef78304bc4f5558439b65955119806e4fb3fe"
  ["rawString"] => string(205) "jsapi_ticket=HoagFKDcsGMVCIY2vOjf9raVdUJqZ1stwmkyXwhMyovuJhCTHjtpRnNxRJSVQ0UacAdrqz97vWdzjRU3Dp-YYw&noncestr=5cKMHQADQTbRkv2f*tamp=1527576256&url=http://www.xiangtws.com/index.php/Wx/Prodetail/index/id/20/"
}
*
*/		//dump($signPackage);
		$this->assign('signPackage',$signPackage);//微信数据
//微信分享-end
		//未关注的存储到xcache中，程序轮询检测（关注后推送最近浏览的商品信息）-start
		if(session('focus')==0 && session('u_id')>0){
			$focusmsg=new \Wx\Controller\AutofocusmsgController();  //用绝对路径找
			$focusmsg->setxcache(session('u_id'),$shop['title'],'http://www.xiangtws.com'.$_SERVER['REQUEST_URI']);
		}//end if
		//未关注的存储到xcache中，程序轮询检测（关注后推送最近浏览的商品信息）-end
		
        $this->display("prodetail");
    }//end fun index

    //检测用户信息是否完善
	public function checkuser(){
		$member=D('member');//用户表
		if(session('u_id')){
			//已经登录
			//信息监测
			$data=array();
			$getinfo=$member->where("id=".session('u_id'))->find();
			if(session('focus')==0){
				$data['state']="focus";
				//需要关注
				$this->ajaxReturn($data,'json');
			}
			if($getinfo['realname'] && $getinfo['mobile'] && $getinfo['c_id'] && $getinfo['hometown']){
				$data['state']="ok";
				//信息全
				//同小区监测
				if($_POST['comid']>0 && $_POST['comid']!=$getinfo['c_id']){
					$data['this_comid']=$_POST['comid'];
					$data['my_comid']=$getinfo['c_id'];
					$data['state']="otherarea";
				}
				//特殊情况，如果用户之间分享了门店url给朋友，而不是购买付款后跳转带有c_id的url
				if($_POST['comid']==0){
					$shop_spellgroup=D('shop_spellgroup');
					$getshop=$shop_spellgroup->where("id=".$_POST['sg_id'])->find();
					if($getshop['type']==1){
						$shop_store=D('shop_store');
						$getstore=$shop_store->where("id=".$getshop['s_id'])->find();
						if($getstore['c_id']!=$getinfo['c_id']){
							//门店拼团的和用户不在一个小区
							$data['this_comid']=$_POST['comid'];
							$data['my_comid']=$getinfo['c_id'];
							$data['state']="otherarea";
							
						}
					}
				}
				//特殊情况，如果用户之间分享了门店url给朋友，而不是购买付款后跳转带有c_id的url--end
			}else{
				//session("pro_url",$_POST['url']);
				$data['state']="need";
				//需要补充信息
				$this->ajaxReturn($data,'json');
			}
			$this->ajaxReturn($data,'json');
		}else{
			//未登录
			//获取openid
			//获取当前网页，授权后跳回
			//session("pro_url",$_POST['url']);
			$path=session("pro_url");
			//跳转到微信授权
			$path='/Wx/Auth/index?path='.$path;
			$data['state']="login";
			$data['url']=$path;
			$this->ajaxReturn($data,'json');//跳转登录+返回当前页面
		}//end if
	}//end fun

    //添加收藏
    public function addCollect(){
        if(IS_POST){
            $post['group_id'] = intval(I('group_id'));
            $post['u_id'] = session('u_id');
            $post['addtime'] = time();
            $res = M('shop_spellgroup_collection')->add($post);
            if($res){
                $this->success('收藏成功');
            }
        }else{
            $this->error('非法进入');
        }
    }//end fun addCollect()

    // 取消收藏
    public function cancleCollect(){
        if(IS_POST){
            $where['group_id'] = intval(I('group_id'));
            $where['u_id'] = session('u_id');
            $res = M('shop_spellgroup_collection')->where($where)->delete();
            if($res){
                $this->success('取消收藏成功');
            }
        }else{
            $this->error('非法进入');
        }

    }//end fun cancleCollect()



}//end class